<template>
  <div class="top-navigation">
    <!-- 左侧区域 -->
    <div class="left-section">
      <DropdownPanel class="nav-item" :delay="200">
        <template #trigger>
          <span class="welcome-text">{{ selectedRegion }} - by |</span>
        </template>
        <template #content>
          <div class="dropdown-content region-dropdown">
            <a v-for="region in regions" :key="region.value" href="#" class="dropdown-item"
              :class="{ 'active': region.value === selectedRegion }" @click.prevent="selectRegion(region.value)">
              {{ region.label }}
            </a>
          </div>
        </template>
      </DropdownPanel>
      <!-- 根据登录状态显示不同内容 -->
      <!-- <template v-if="authStore.isLoggedIn">
        <a href="#" class="auth-link">你好，<span>{{ authStore.username }}</span></a>
        <span class="divider">|</span>
        <a href="#" class="auth-link" @click.prevent="handleLogout">退出登录</a>
      </template> -->
      <template v-if="authStore.isLoggedIn">
        <!-- 用 DropdownPanel 包裹，实现下拉效果 -->
        <DropdownPanel class="nav-item" :delay="200">
          <template #trigger>
            <a href="#" class="auth-link">
              你好，<span>{{ authStore.username }}</span>
            </a>
          </template>
          <template #content>
            <!-- 这里定义下拉框内容，可根据需求自定义，风格和现有下拉菜单保持一致 -->
            <div class="dropdown-content login-dropdown">
             <UserDropdown />
            </div>
          </template>
        </DropdownPanel>
        <span class="divider">|</span>
        <a href="#" class="auth-link" @click.prevent="handleLogout">退出登录</a>
      </template>
      <template v-else>
        <a href="#" class="auth-link" @click.prevent="handleLoginClick">你好，<span>请登录</span></a>
        <span class="divider">|</span>
        <a href="#" class="auth-link" @click="goRegister">免费注册</a>
      </template>
      <a href="#" class="enterprise-link"> | 切换至企业版</a>
    </div>

    <!-- 右侧导航 -->
    <div class="right-section">
      <template v-for="item in navItems" :key="item.text">
        <!-- 有下拉内容的项 -->
        <DropdownPanel v-if="item.dropdown" class="nav-item" :delay="item.delay || 200">
          <template #trigger>
            <a :href="item.link" @click.prevent="handleNavClick(item)">
              <i v-if="item.icon" :class="item.icon"></i>
              <span v-if="item.isCart">购物车({{ authStore.isLoggedIn ? cartStore.totalCount : 0 }})</span>
              <span v-else>{{ item.text }} | </span>
            </a>
          </template>
          <template #content>
            <!-- 普通下拉菜单 -->
            <div v-if="item.text !== '手机京东'" class="dropdown-content">
              <a v-for="(subItem, index) in item.dropdown" :key="index" :href="subItem.link" class="dropdown-item"
                @click.prevent="handleNavClick(subItem)">
                {{ subItem.text }}
              </a>
            </div>

            <!-- 手机京东特殊下拉菜单 -->
            <div v-else class="mobile-dropdown-content">
              <div class="mobile-apps-list">
                <a v-for="(subItem, index) in item.dropdown" :key="index" :href="subItem.link" class="mobile-app-item"
                  @click.prevent="handleNavClick(subItem)">
                  <img :src="subItem.url" :alt="subItem.text">
                  <div class="app-info">
                    <p class="app-title">{{ subItem.text }}</p>
                    <p class="app-subtitle">{{ subItem.subtitle }}</p>
                  </div>
                </a>
              </div>
            </div>
          </template>
        </DropdownPanel>

        <!-- 无下拉内容的项 -->
        <a v-else :href="item.link" class="nav-item" @click.prevent="handleNavClick(item)">
          <i v-if="item.icon" :class="item.icon"></i>
          <span v-if="item.isCart">购物车({{ authStore.isLoggedIn ? cartStore.totalCount : 0 }})</span>
          <span v-else>{{ item.text }}</span>
        </a>
      </template>
    </div>

    <!-- 登录弹窗组件 -->
    <LoginDialog v-model="dialogVisible" />

    <!-- 无障碍工具栏组件 -->
    <AccessibilityToolbar :visible="isToolbarVisible" @close="isToolbarVisible = false" @open="isToolbarVisible = true"
      @screen-reader="handleScreenReader" @sound-toggle="handleSoundToggle" @speech-rate="handleSpeechRate"
      @reading-mode="handleReadingMode" @color-scheme="handleColorScheme" @zoom-in="handleZoomIn"
      @zoom-out="handleZoomOut" @reset="handleReset" />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useAuthStore } from '@/stores/auth';
import { useCartStore } from '@/stores/cart';
import LoginDialog from '@/components/login/LoginDialog.vue';
import DropdownPanel from '@/components/Dropdown/DropdownPanel.vue';
import UserDropdown from './UserDropdown.vue'; // 引入用户下拉菜单组件
import AccessibilityToolbar from './AccessibilityToolbar.vue'; // 引入无障碍工具栏组件
import router from '@/router';
import { ElMessage } from 'element-plus'
import { useLanguageStore } from '@/stores/language';

const dialogVisible = ref(false);
const cartStore = useCartStore();
const authStore = useAuthStore();
// 无障碍工具栏显示状态
const isToolbarVisible = ref(false);

// 组件挂载时初始化用户状态
authStore.initialize();

const handleLoginClick = () => {
  dialogVisible.value = true;
};

const handleLogout = async () => {
  try {
    await authStore.logout();
  } catch {
    ElMessage.error('退出登录失败');
  }
};

const goRegister = () => {
  router.push('./register');
};

const handleNavClick = (item) => {
  // 如果点击的是"网站无障碍"，则切换工具栏显示状态
  if (item.text === '网站无障碍') {
    toggleToolbar();
    return;
  }

  if (item.link && item.link !== '#') {
    router.push(item.link);
  }
};

// 切换无障碍工具栏显示/隐藏
const toggleToolbar = () => {
  isToolbarVisible.value = !isToolbarVisible.value;
};
// 无障碍工具栏各功能的处理函数
const handleScreenReader = () => {
  // 实际项目中实现读屏功能
  console.log('读屏功能激活');
};

const handleSoundToggle = () => {
  // 实际项目中实现声音开关功能
  console.log('声音开关切换');
};

const handleSpeechRate = () => {
  // 实际项目中实现语速调整功能
  console.log('语速调整');
};

const handleReadingMode = () => {
  // 实际项目中实现阅读方式切换功能
  console.log('阅读方式切换');
};

const handleColorScheme = () => {
  // 实际项目中实现配色方案切换功能
  console.log('配色方案切换');
};

const handleZoomIn = () => {
  // 实际项目中实现页面放大功能
  console.log('页面放大');
};

const handleZoomOut = () => {
  // 实际项目中实现页面缩小功能
  console.log('页面缩小');
};

const handleReset = () => {
  // 实际项目中实现重置功能
  console.log('所有设置重置');
};

// 导入图片
import jd_img1 from '@/assets/imgs/login/jd_qcode1.png';
import jd_img2 from '@/assets/imgs/login/jd_qcode2.png';
import jd_img3 from '@/assets/imgs/login/jd_qcode3.png';
import jd_img4 from '@/assets/imgs/login/jd_qcode4.png';
import jd_img5 from '@/assets/imgs/login/jd_qcode5.png';
const navItems = ref([
  {
    text: '购物车',
    link: '/cart',
    icon: 'iconfont icon-gouwuche',
    isCart: true
  },
  {
    text: '我的订单',
    link: '#'
  },
  {
    text: '我的京东',
    link: '#',
    dropdown: [
      { text: '待处理订单', link: '#' },
      { text: '我的问答', link: '#' },
      { text: '降价商品', link: '#' },
      { text: '返修退换货', link: '#' },
      { text: '我的关注', link: '#' }
    ]
  },
  {
    text: '企业采购',
    link: '#',
    dropdown: [
      { text: '企业购首页', link: '#' },
      { text: '采购需求', link: '#' },
      { text: '采购单管理', link: '#' },
      { text: '供应商管理', link: '#' }
    ]
  },
  {
    text: '商家服务',
    link: '#',
    dropdown: [
      { text: '商家后台', link: '#' },
      { text: '入驻申请', link: '#' },
      { text: '商家培训', link: '#' },
      { text: '营销工具', link: '#' }
    ]
  },
  {
    text: '网站导航',
    link: '#',
    dropdown: [
      { text: '全部分类', link: '#' },
      { text: '特色市场', link: '#' },
      { text: '品牌精选', link: '#' },
      { text: '京东超市', link: '#' }
    ]
  },
  {
    text: '手机京东',
    link: '#',
    dropdown: [
      { url: jd_img1, text: '手机京东', subtitle: '新人专享大礼包', link: '#' },
      { url: jd_img2, text: '关注京东JD.COM', subtitle: '天天抢红包', link: '#' },
      { url: jd_img3, text: '京东金融客户端', subtitle: '新人专享大礼包', link: '#' },
      { url: jd_img4, text: '京东健康客户端', subtitle: '', link: '#' },
      { url: jd_img5, text: '关注京东小程序', subtitle: '新人0.1元购', link: '#' }
    ]
  },
  {
    text: '网站无障碍',
    link: '#'
  }
]);
const regions = [
  { value: '中国大陆版', label: '中国大陆版' },
  { value: '香港版', label: '香港版' },
  { value: '台湾版', label: '台湾版' },
  { value: '国际版', label: '国际版' }
];

// 当前选中的地区
const selectedRegion = ref('中国大陆版');

// 导入翻译函数
import { translateToHK } from '@/utils/translateToHK';
import { translateToTW } from '@/utils/translateToTW';
import { translateToEN } from '@/utils/translateToEN';

// 获取语言 store
const languageStore = useLanguageStore();
// 修改 selectRegion 函数
const selectRegion = (region) => {
  selectedRegion.value = region;
  languageStore.setLanguage(region);
  // 保存语言设置到本地存储
  localStorage.setItem('selectedLanguage', region);
};

// 监听语言变化，更新导航项文本
watch(
  () => languageStore.currentLanguage,
  (newLanguage) => {
    const translateFunction = {
      '香港版': translateToHK,
      '台湾版': translateToTW,
      '国际版': translateToEN,
      '中国大陆版': (text) => text
    }[newLanguage];

    // 更新导航项文本，添加安全检查
    navItems.value = navItems.value.map(item => ({
      ...item,
      text: item.text ? translateFunction(item.text) : '',
      dropdown: item.dropdown ? item.dropdown.map(subItem => ({
        ...subItem,
        text: subItem.text ? translateFunction(subItem.text) : '',
        subtitle: subItem.subtitle ? translateFunction(subItem.subtitle) : ''
      })) : undefined
    }));
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.top-navigation {
  background-color: rgb(255, 255, 255);
  height: 36px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  font-size: 12px;
  color: #999;
  border-bottom: 1px solid #e5e5e5;
  position: relative; // 为无障碍工具栏提供定位上下文

  .left-section {
    display: flex;
    align-items: center;
    gap: 10px;

    .nav-item {
      display: inline-block;
      position: relative;

      .welcome-text {
        color: #999;
        cursor: pointer;

        &:hover {
          color: rgb(255, 15, 35);
        }
      }

      .region-dropdown {
        left: 0;
        top: 100%;
        display: flex;
        flex-direction: column;
        padding: 5px;
        background: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

        .dropdown-item {
          padding: 4px 8px;
          color: #666;
          text-decoration: none;
          font-size: 12px;
          white-space: nowrap;
          text-align: center;

          &:hover {
            color: #e4393c;
            background-color: #e4393c;
            color: white;
          }
        }
      }
    }

    .auth-link {
      color: rgb(80, 82, 89);
      text-decoration: none;

      span {
        color: rgb(241, 29, 45);
      }

      &:hover {
        text-decoration: underline;
        color: rgb(241, 29, 45);
      }
    }

    .login-dropdown {
      background-color: #d33d3d;
      .top-header{
        display: flex;
        // flex-direction: row;
        img{
          width: 50px;
          height: 50px;
        }
      }
    }

    .divider {
      color: #ccc;
    }

    .enterprise-link {
      color: #666;
      text-decoration: none;

      &:hover {
        color: #e4393c;
      }
    }
  }

  .right-section {
    display: flex;
    align-items: center;
    gap: 15px;

    .nav-item {
      color: #666;
      text-decoration: none;
      display: flex;
      align-items: center;
      gap: 4px;
      position: relative;

      a {
        text-decoration: none;
        color: rgb(80, 82, 89);
      }

      .iconfont {
        color: rgb(255, 45, 63);
      }

      &:hover {
        color: #e4393c;
      }

      .iconfont {
        font-size: 14px;
      }
    }

    /* 普通下拉菜单样式 */
    .dropdown-content {
      display: flex;
      flex-direction: column;
      min-width: 120px;
      padding: 8px 0;
      background: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

      .dropdown-item {
        padding: 8px 15px;
        color: #666;
        text-decoration: none;
        font-size: 12px;
        white-space: nowrap;

        &:hover {
          color: #e4393c;
          background-color: #f5f5f5;
        }
      }
    }

    /* 手机京东特殊下拉菜单样式 - 单列布局 */
    .mobile-dropdown-content {
      width: 200px;
      padding: 10px 0;
      background: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

      .mobile-apps-list {
        display: flex;
        flex-direction: column;
        gap: 8px;

        .mobile-app-item {
          display: flex;
          align-items: center;
          padding: 8px 15px;
          text-decoration: none;
          color: #333;
          transition: background-color 0.2s;

          &:hover {
            background-color: #f5f5f5;
          }

          img {
            width: 36px;
            height: 36px;
            margin-right: 10px;
            object-fit: contain;
          }

          .app-info {
            display: flex;
            flex-direction: column;
            justify-content: center;

            .app-title {
              font-size: 10px;
              color: rgb(102, 102, 102);
            }

            .app-subtitle {
              font-size: 8px;
              color: red;
            }
          }
        }
      }
    }
  }
}
</style>
